package org.ls.petclinic.filter;


import org.ls.petclinic.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 浪矢先生
 */
public class ManagerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        String uri = httpServletRequest.getRequestURI();
        httpServletRequest.setCharacterEncoding("UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        //过滤登录请求
        if (
                 uri.equals(httpServletRequest.getContextPath()+"/login")
               ||uri.equals(httpServletRequest.getContextPath()+"jsp/login.jsp")
               ||uri.equals(httpServletRequest.getContextPath()+"/")
        ){
            filterChain.doFilter(servletRequest, servletResponse);
        }
       else  {
          User user= (User) httpServletRequest.getSession().getAttribute("user");
        if (user==null){
            servletRequest.getRequestDispatcher("/jsp/login.jsp").forward(servletRequest, servletResponse);
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        }
    }

    @Override
    public void destroy() {

    }
}
